# 导包
import tornado.web

# 服务器
from tornado import httpserver

# 导入基础类
from base import BaseHandler

# 导入数据库操作类
from db import database,User,myser,MyMongo,Talk,Subject,Sub_Talk,Comment

# 异步执行库
import peewee_async
import hashlib

import json

from tools import ret_json,send_mail,MyJwt,ImgList,Flow

from playhouse.shortcuts import model_to_dict

from test_desgin import SimpleFactory

import random
import datetime
import re

import pytz
# 设置时区
tzinfo = pytz.timezone('Asia/Shanghai')

import requests

# 绘图库

from PIL import ImageDraw
from PIL import Image

# io库
import io

# 时间模块
import time


import base64
import hmac
from hashlib import sha256

import urllib

import re

import os

# 导入聚合查询库
from peewee import fn


# 帖子评论接口
class CommentView(BaseHandler):

	# 添加评论
	async def post(self):

		sid = self.get_argument("sid",None)
		uid = self.get_argument("uid",None)
		content = self.get_argument("content",None)
		touid = self.get_argument("touid",0)


		# 入库
		comment = await self.application.objects.create(Comment,sid=sid,uid=uid,content=content,touid=touid)


		return self.write(ret_json({"code":200,"msg":"评论成功","cid":comment.id}))

	# 展示评论
	async def get(self):

		sid = self.get_argument("sid",None)

		comments = await self.application.objects.execute(Comment.select().where(Comment.sid==sid).order_by(-Comment.id))

		comments = [myser(x) for x in comments]

		return self.write(ret_json(comments))


# 关注接口
class FlowView(BaseHandler):

	async def get(self):

		uid = self.get_argument("uid",None)

		fuid = self.get_argument("fuid",None)

		flow = Flow()

		res = flow.if_flow(uid,fuid)

		print(res)

		if res == True:

			res = 1
		else:
			res = 0

		return self.write({"state":res})



# 图集接口
class Img(BaseHandler):


	# 删除图集
	async def delete(self):

		# 帖子id
		sid = self.get_argument("sid",None)

		sid = int(sid)

		# 图集列表
		imglist = self.get_argument("imglist",None)

		imglist = eval(imglist)


		# 删除文件名
		filename = self.get_argument("filename",None)

		# 删除文件操作
		os.remove("./static/"+filename)



		myimg = ImgList()
		if imglist:
			# 修改覆盖
			myimg.update_one(sid,imglist)

		else:
			# 删除
			myimg.del_img(sid)

		return self.write(ret_json({"code":200,"msg":"删除图集成功"}))





	# 修改图集
	async def put(self):

		# 帖子id
		sid = self.get_argument("sid",None)

		sid = int(sid)

		# 图集列表
		imglist = self.get_argument("imglist",None)

		imglist = eval(imglist)

		# 修改
		myimg = ImgList()

		# 先查询
		res = myimg.get_img(sid)

		if res:
			myimg.update_one(sid,imglist)
		else:
			myimg.insert_one(sid,imglist)

		return self.write(ret_json({"code":200,"msg":"修改图集成功"}))


	# 插入图集
	async def post(self):

		 # 帖子id
		 sid = self.get_argument("sid",None)

		 sid = int(sid)

		 # 图集列表
		 imglist = self.get_argument("imglist",None)

		 imglist = eval(imglist)

		 print(imglist)

		 print(type(imglist))

		 # 入库
		 myimg = ImgList()

		 # 查询

		 # img = myimg.get_img(sid)

		 # if img:
		 # 	return self.write(ret_json({"code":403,"msg":"该帖子已经存在"}))
		 # else:
		 # 	myimg.insert_one(sid,imglist)
		 # 	return self.write(ret_json({"code":200,"msg":"插入图集成功"}))
		 try:
		 	myimg.insert_one(sid,imglist)
		 	return self.write(ret_json({"code":200,"msg":"插入图集成功"}))
		 except Exception as e:
		 	return self.write(ret_json({"code":403,"msg":"该帖子已经存在"}))

		 



# 可at用户列表
class AtUser(BaseHandler):

	async def get(self):

		# 用户id
		id = self.get_argument("id",None)

		# 排除查询
		#users = await self.application.objects.execute(User.select().where(User.id!=id))
		users = await self.application.objects.execute(User.select())

		# 序列化
		users = [myser(x) for x in users]

		return self.write(ret_json(users))




# 帖子类
class SubjectView(BaseHandler):

	# 删除帖子
	async def delete(self):

		# 帖子id
		id = self.get_argument("id",None)

		id = int(id)


		# 异步删除
		sub = await self.application.objects.get(Subject,id=id)
		await self.application.objects.delete(sub)

		myimg = ImgList()

		# 删除物理文件
		imglist = myimg.get_img(id)

		for x in imglist:
			try:
				os.remove("./static/%s" % x)
			except Exception as e:
				pass

		# 删除对应图集
		
		myimg.del_img(id)

		return self.write(ret_json({"code":200,"msg":"删除成功"}))



	# 查询当前账号帖子
	async def get(self):

		uid = self.get_argument("uid",None)
		# 当前页
		page = self.get_argument("page",1)

		page = int(page)

		# 查询帖子评论数
		comments = await self.application.objects.execute(Comment.select(Comment.sid,fn.COUNT(Comment.id).alias("total")).group_by(Comment.sid))


		comment_dict = {}

		for x in comments:
			comment_dict[x.sid] = x.total

		print(comment_dict)

		# 异步查询  分页器  当前页  每页有多少条
		subs = await self.application.objects.execute(Subject.select().where(Subject.uid==uid).paginate(page,10).order_by(-Subject.id))

		# 获取总个数
		total = await self.application.objects.count(Subject.select().where(Subject.uid==uid))

		# 算一共多少页
		if total % 10 == 0:

			allpage =  total // 10

		else:

			allpage =  total // 10 + 1

		# 序列化
		subs = [myser(x) for x in subs]

		# 正则解析帖子内容，查看有多少at用户
		username_dict = {}
		for x in subs:

			# 增加评论数
			x["comment"] = comment_dict.get(x["id"],0)

			users = re.findall(r'@([\w]+)',x["info"])

			# 查询用户的id
			for user in users:

				# 查询用户id
				try:
					uid = await self.application.objects.get(User.select().where(User.username==user))
					# 用户名为key id 为值  {"吴帅康":50}
					username_dict[user] = uid.id
					x["info"] = x["info"].replace("@%s" % user,"<a href='/userinfo/?uid=%s'>@%s</a>" % (username_dict[user],user))
				except Exception as e:
					pass

			# 替换逻辑  <a href='@吴帅康'>@吴帅康</a>
			#res = re.sub(r'@([\w]+)',"<a href='\g<0>'>\g<0></a>",x["info"])



		# 查询图集
		mymongo = MyMongo("img")

		imgs = mymongo.find({})

		imgs_dict = {}

		for x in imgs:

			imgs_dict[x['sid']] = x['imglist']

		for x in subs:

			x["imglist"] = imgs_dict.get(x["id"],[])

		data = {}
		data["allpage"] = allpage
		data["data"] = subs

		return self.write(ret_json(data))


	# 修改帖子
	async def put(self):

		sid = self.get_argument("sid",None)

		# 内容
		info = self.get_argument("info",None)

		# 类型
		type = self.get_argument("type",0)

		# 解析帖子内容，查看参与话题
		talks = re.findall(r'#([\w]+)#',info)

		if talks:
			# 入库操作
			for x in talks:
				try:
					await self.application.objects.create(Talk,title=x)
				except Exception as e:
					pass

		# 修改帖子
		sub = await self.application.objects.get(Subject.select().where(Subject.id==sid))

		# 赋值操作
		sub.info = info
		sub.type = type

		# 保存
		await self.application.objects.update(sub)

		# 删除关联话题
		sub_talk = await self.application.objects.execute(Sub_Talk.select().where(Sub_Talk.sid==sid))

		for x in sub_talk:
			# 删除操作
			await self.application.objects.delete(x)

		# 反查话题id
		if talks:

			for x in talks:

				talkid = await self.application.objects.get(Talk,title=x)

				# 入库
				await self.application.objects.create(Sub_Talk,sid=sub.id,tid=talkid.id)

		return self.write(ret_json({"code":200,"msg":"修改成功"}))












	# 创建帖子
	async def post(self):

		# 用户id
		uid = self.get_argument("uid",None)

		# 内容
		info = self.get_argument("info",None)

		# 类型
		type = self.get_argument("type",0)

		# 图片
		img = self.get_argument("img",None)

		# 视频
		video = self.get_argument("video",None)

		# 解析帖子内容，查看参与话题
		talks = re.findall(r'#([\w]+)#',info)

		if talks:
			# 入库操作
			for x in talks:
				try:
					await self.application.objects.create(Talk,title=x)
				except Exception as e:
					pass

		# 创建帖子
		sub = await self.application.objects.create(Subject,uid=uid,info=info,type=type,img=img,video=video)

		# 反查话题id
		if talks:

			for x in talks:

				talkid = await self.application.objects.get(Talk,title=x)

				# 入库
				await self.application.objects.create(Sub_Talk,sid=sub.id,tid=talkid.id)

		return self.write(ret_json({"code":200,"msg":"创建帖子成功","sid":sub.id}))


# 单帖数据
class OneSub(SubjectView):

	async def get(self):

		sid = self.get_argument("sid",None)

		# 数据库查询
		try:
			sub = await self.application.objects.get(Subject.select().where(Subject.id==sid))
		except Exception as e:
			return self.write(ret_json({"code":403,"msg":"您所请求的帖子不存在"}))

		# 序列化
		sub = myser(sub)

		print(sub)

		# 获取图集
		myimg = ImgList()

		imglist = myimg.get_img(int(sid))

		print(imglist)

		# 赋值
		sub["imglist"] = imglist

		return self.write(ret_json(sub))











